package com.boot.netty.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class ToServerHandler extends ChannelInboundHandlerAdapter {
    private Map<Channel, Channel> map = null;

    public ToServerHandler(Map<Channel, Channel> channelMap) {
        this.map = channelMap;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("代理到目标服务器的channel handler出错：");
        cause.printStackTrace();
        if (map.containsKey(ctx.channel())) {
            map.remove(ctx.channel());
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel serverChannel = ctx.channel();
        Channel clientChannel = map.get(serverChannel);
        clientChannel.writeAndFlush(msg);
        log.info("serverChannel:{}", serverChannel);
        log.info("clientChannel:{}", clientChannel);
    }
}
